package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.*;
import com.sky.exception.BaseException;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.AdminSocket;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    AddressBookMapper addressBookMapper;
    @Autowired
    OrderDetaillMapper orderDetaillMapper;
    @Autowired
    ShoppingCartMapper shoppingCartMapper;
    @Autowired
    WeChatPayUtil weChatPayUtil;
    @Autowired
    AdminSocket adminSocket;

    @Override
    @Transactional
    public OrderSubmitVO addOrder(OrdersSubmitDTO ordersSubmitDTO) {
        //处理异常 地址为空,购物车为空
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new BaseException("地址未输入哟~~");
        }
        Long currentId = BaseContext.getCurrentId();
        List<ShoppingCart> all = shoppingCartMapper.getAll(currentId);
        if (all == null && all.size() == 0) {
            throw new BaseException("购物车为空,挑点东西呗");
        }
        String ordername = String.valueOf(System.currentTimeMillis());
        LocalDateTime now = LocalDateTime.now();
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setOrderTime(now);
        orders.setPayStatus(Orders.UN_PAID);
        orders.setNumber(ordername);
        orders.setPhone(addressBook.getPhone());
        orders.setStatus(1);
        orders.setConsignee(addressBook.getConsignee());
        orders.setUserId(currentId);
        Long orderId = orderMapper.add(orders);
        //明细表插入
        List<OrderDetail> orderDetails = new ArrayList<>();
        all.forEach(shoppingCart -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, orderDetail);
            orderDetail.setOrderId(orderId);
            orderDetails.add(orderDetail);
        });
        orderDetaillMapper.add(orderDetails);
        OrderSubmitVO submitVO = new OrderSubmitVO();
        submitVO.setId(orderId);
        submitVO.setOrderAmount(ordersSubmitDTO.getAmount());
        submitVO.setOrderNumber(ordername);
        submitVO.setOrderTime(now);
        //清空购物车
        shoppingCartMapper.cleanAll(currentId);
        //JSONObject封装
        JSONObject jsonobject = new JSONObject();
        jsonobject.put("type", 1);
        jsonobject.put("orderId", orderId);
        jsonobject.put("content", "订单号" + ordername);
//        System.out.println(jsonobject.toJSONString());
       /* //Map封装
        Map map = new HashMap();
        map.put("type",1);
        map.put("orderId",orderId);
        map.put("content","订单号"+ordername);
        System.out.println(JSON.toJSONString(map));*/
        adminSocket.sendToAllClient(jsonobject.toJSONString());
        return submitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);
        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );
        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));
        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders);
    }

    @Override
    public PageResult page(OrdersPageQueryDTO queryDTO) {
        PageHelper.startPage(queryDTO.getPage(), queryDTO.getPageSize());
        Page<Orders> orders = orderMapper.getByStatus(queryDTO);
        return new PageResult(orders.getTotal(), orders.getResult());
    }

    @Override
    public OrderVO getDetailById(Long orderId) {
        Orders orders = orderMapper.getById(orderId);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetaillMapper.getByOrderId(orderId));
        return orderVO;
    }

    @Override
    public void cancelOrder(Long orderId) {
        //修改总表
        Orders orders = Orders.builder().id(orderId).status(6).payStatus(2).cancelTime(LocalDateTime.now()).cancelReason("用户取消").build();
        orderMapper.update(orders);
        //不用修改详细表
    }

    @Override
    public void again(Long id) {
        //将购物车清空
        shoppingCartMapper.cleanAll(BaseContext.getCurrentId());
        List<OrderDetail> detailList = orderDetaillMapper.getByOrderId(id);
        List<ShoppingCart> shoppingCarts = new ArrayList<>();
        detailList.forEach(d -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(d, shoppingCart);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCarts.add(shoppingCart);
        });
        //将原本信息添加到购物车
        shoppingCartMapper.addByList(shoppingCarts);
    }

    @Override
    public void reminder(Long id) {
        Orders byId = orderMapper.getById(id);
        JSONObject jsonObject = new JSONObject();
        //JSONObject封装
        JSONObject jsonobject = new JSONObject();
        jsonobject.put("type", 2);
        jsonobject.put("orderId", byId.getId());
        jsonobject.put("content", "订单号" + byId.getNumber());
        adminSocket.sendToAllClient(jsonobject.toJSONString());
    }
}
